﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace Hands.UriRewrite
{
    public class RewriteHttpModule : IHttpModule
    {
        #region IHttpModule 成员

        public void Dispose()
        {
            //no op for this method
        }

        public void Init(HttpApplication context)
        {
            context.BeginRequest += beginRequest;
        }

        private HttpContext context = null;

        private delegate IRewrite QueryEventHandler(string path);
        private delegate string RewriteEventHandler(string path);

        private void beginRequest(object sender, EventArgs e)
        {
            HttpApplication application = (HttpApplication)sender;
            context = application.Context;

            string path = context.Request.Url.AbsolutePath;

            QueryEventHandler queryHandler = new QueryEventHandler(new UriRootPathQuery().find);
            IRewrite rewrite = queryHandler.Invoke(path);

            if (rewrite != null)
            {
                RewriteEventHandler rewriteHandler = new RewriteEventHandler(rewrite.rewrite);
                string rewritePath = rewriteHandler.Invoke(path);
                if (rewritePath.Length != 0)
                {
                    context.RewritePath("~" + rewritePath);
                }
            }
        }
        #endregion
    }
}
